﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Ccit.ClassLibrary;
using Ccit.SysPlat.Log;
using System.Web;

namespace Ccit.Utils
{
    /// <summary>
    /// 控件操作类
    /// </summary>
    public class CtrInterface
    {
        #region init error log interface
        private static ILog _logInterface = Factory.CreateObject(MsErrLog.assemblyName, MsErrLog.className,
                                                    ImportComponentType.DotNetDll, null) as ILog;
        private const string _funcPageName = "通用接口";
        private static string _dbType = HttpContext.Current.Application["DBType"].ToString();
        #endregion


        #region public static interface

        /// <summary>
        /// 绑定通用DropDownList
        /// </summary>
        /// <param name="ddl">dropdownlist 控件</param>
        /// <param name="tableName">数据表表名</param>
        /// <param name="primaryKey">主键字段</param>
        /// <param name="nameField">名称字段</param>
        /// <param name="emptyHeader">是否有空头项</param>
        /// <param name="headerText">空头显示文本</param>
        public static void BindDropDown(ref DropDownList ddl, string tableName, string primaryKey,
                                    string nameField, bool emptyHeader, string headerText)
        {
            ddl.Items.Clear();
            string cmdText = "SELECT " + primaryKey + " AS ID," + nameField + " AS NAME FROM " + tableName;
            ListItem li;
            if (emptyHeader)
                ddl.Items.Add(new ListItem(headerText, ""));

            using (IDataReader reader = DataAccessor.ExecuteReader(cmdText))
            {
                while (reader.Read())
                {
                    li = new ListItem(reader["NAME"].ToString(), reader["ID"].ToString());
                    ddl.Items.Add(li);
                }
            }
        }

        /// <summary>
        /// 绑定通用DropDownList
        /// </summary>
        /// <param name="ddl">dropdownlist 控件</param>
        /// <param name="tableName">数据表表名</param>
        /// <param name="primaryKey">主键字段</param>
        /// <param name="nameField">名称字段</param>
        /// <param name="emptyHeader">是否有空头项</param>
        /// <param name="headerText">空头显示文本</param>
        /// <param name="whereClause">过滤条件</param>
        public static void BindDropDown(ref DropDownList ddl, string tableName, string primaryKey,
                                    string nameField, bool emptyHeader, string headerText,string whereClause)
        {
            ddl.Items.Clear();
            string cmdText = "SELECT " + primaryKey + " AS ID," + nameField + " AS NAME FROM " + tableName;
            string sQryCon = (!string.IsNullOrEmpty(whereClause)) ? whereClause : "1=1";
            cmdText += " WHERE " + sQryCon;
            ListItem li;
            if (emptyHeader)
                ddl.Items.Add(new ListItem(headerText, ""));

            using (IDataReader reader = DataAccessor.ExecuteReader(cmdText))
            {
                while (reader.Read())
                {
                    li = new ListItem(reader["NAME"].ToString(), reader["ID"].ToString());
                    ddl.Items.Add(li);
                }
            }
        }

        /// <summary>
        /// 绑定通用htmlselect
        /// </summary>
        /// <param name="htSel">select 控件</param>
        /// <param name="tableName">数据表表名</param>
        /// <param name="primaryKey">主键字段</param>
        /// <param name="nameField">名称字段</param>
        /// <param name="emptyHeader">是否有空头项</param>
        /// <param name="headerText">空头显示文本</param>
        /// <param name="whereClause">过滤条件</param>
        public static void BindDropDown(ref HtmlSelect htSel, string tableName, string primaryKey,
                                    string nameField, bool emptyHeader, string headerText, string whereClause)
        {
            htSel.Items.Clear();
            string cmdText = "SELECT " + primaryKey + " AS ID," + nameField + " AS NAME FROM " + tableName;
            string sQryCon = (!string.IsNullOrEmpty(whereClause)) ? whereClause : "1=1";
            cmdText += " WHERE " + sQryCon;
            ListItem li;
            if (emptyHeader)
                htSel.Items.Add(new ListItem(headerText, ""));

            using (IDataReader reader = DataAccessor.ExecuteReader(cmdText))
            {
                while (reader.Read())
                {
                    li = new ListItem(reader["NAME"].ToString(), reader["ID"].ToString());
                    htSel.Items.Add(li);
                }
            }
        }

        /// <summary>
        /// 绑定通用DropDownList
        /// </summary>
        /// <param name="ddl">dropdownlist 控件</param>
        /// <param name="lstData">要绑定的数据集合</param>
        /// <param name="isSetSelValue">是否有默认选中项</param>
        /// <param name="selValue">默认选中值</param>
        public static void BindDropDown(ref DropDownList ddl, List<MsKeyValue> lstData,bool isSetSelValue,string selValue)
        {
            ddl.Items.Clear();

            if (null != lstData && lstData.Count > 0)
            {
                int itemCount = lstData.Count;
                MsKeyValue msKeyVal;
                
                for (int i = 0; i < itemCount; i++)
                {
                    msKeyVal = lstData[i];
                    ddl.Items.Add(new ListItem(msKeyVal.val, msKeyVal.key));
                }

                if (isSetSelValue)
                {
                    ddl.SelectedValue = selValue;
                }
            }
        }

        /// <summary>
        /// 绑定通用DropDownList
        /// </summary>
        /// <param name="ddl">dropdownlist 控件</param>
        /// <param name="lstData">要绑定的数据集合</param>
        /// <param name="emptyHeader">是否添加空头项</param>
        /// <param name="headerText">空头项显示文本</param>
        /// <param name="isSetSelValue">是否有默认选中项</param>
        /// <param name="selValue">默认选中值</param>
        public static void BindDropDown(ref DropDownList ddl, List<MsKeyValue> lstData,bool emptyHeader,string headerText,
                                        bool isSetSelValue, string selValue)
        {
            ddl.Items.Clear();

            // 添加空头项
            if (emptyHeader)
            {
                ddl.Items.Add(new ListItem { Text = headerText, Value = string.Empty });
            }

            if (null != lstData && lstData.Count > 0)
            {
                int itemCount = lstData.Count;
                MsKeyValue msKeyVal;

                for (int i = 0; i < itemCount; i++)
                {
                    msKeyVal = lstData[i];
                    ddl.Items.Add(new ListItem(msKeyVal.val, msKeyVal.key));
                }

                if (isSetSelValue)
                {
                    ddl.SelectedValue = selValue;
                }
            }
        }

        /// <summary>
        /// 绑定通用htmlSelect
        /// </summary>
        /// <param name="htSel">select 控件</param>
        /// <param name="lstData">要绑定的数据集合</param>
        /// <param name="isSetSelValue">是否有默认选中项</param>
        /// <param name="selValue">默认选中值</param>
        public static void BindDropDown(ref HtmlSelect htSel, List<MsKeyValue> lstData, bool isSetSelValue, string selValue)
        {
            htSel.Items.Clear();

            if (null != lstData && lstData.Count > 0)
            {
                int itemCount = lstData.Count;
                MsKeyValue msKeyVal;

                for (int i = 0; i < itemCount; i++)
                {
                    msKeyVal = lstData[i];
                    htSel.Items.Add(new ListItem(msKeyVal.val, msKeyVal.key));
                }

                if (isSetSelValue)
                {
                    htSel.Value = selValue;
                }
            }
        }


        /// <summary>
        /// 绑定通用DropDownList(按层级编码结构显示)
        /// </summary>
        /// <param name="ddl">dropdownlist 控件</param>
        /// <param name="tableName">数据表表名</param>
        /// <param name="primaryKey">主键字段</param>
        /// <param name="nameField">名称字段</param>
        /// <param name="layCodeField">层级编码字段</param>
        /// <param name="filterId">要过滤掉的主键节点ID及其下的子节点</param>
        /// <param name="iCodeLen"> 每级层级编码长度(如：4位一编码则传入4)</param>
        /// <param name="emptyHeader">是否有空头项</param>
        /// <param name="headerText">空头显示文本</param>
        /// <param name="whereClause">过滤条件</param>
        public static void BindDropDown(ref DropDownList ddl, string tableName, string primaryKey, string nameField, string layCodeField,
                                                    string filterId, int iCodeLen, bool emptyHeader, string headerText, string whereClause)
        {
            ddl.Items.Clear();

            filterId = (string.IsNullOrEmpty(filterId) && (_dbType == "4")) ? "NULL" : filterId;
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT ").Append(primaryKey).Append(" AS ID,").Append(nameField).Append(" AS NAME,").Append(layCodeField).Append(" AS LAYCODE FROM ").Append(tableName).Append(" ");
            sbCmdText.Append("WHERE ").Append(primaryKey).Append(" NOT IN (SELECT ").Append(primaryKey).Append(" FROM ").Append(tableName).Append(" WHERE ");
            if(_dbType == "4") //ACCESS
                sbCmdText.Append(layCodeField).Append(" LIKE (SELECT ").Append(layCodeField).Append(" FROM ").Append(tableName).Append(" WHERE ").Append(primaryKey).Append("=").Append(filterId).Append(") + '%') ");
            else //SQL SERVER、ORACLE
                sbCmdText.Append(layCodeField).Append(" LIKE (SELECT ").Append(layCodeField).Append(" FROM ").Append(tableName).Append(" WHERE ").Append(primaryKey).Append("='").Append(filterId).Append("') + '%') ");
            sbCmdText.Append("AND ");
            string sQryCon = (!string.IsNullOrEmpty(whereClause)) ? whereClause : "1=1";
            sbCmdText.Append(sQryCon).Append(" ORDER BY ").Append(layCodeField);

            ListItem li;
            if (emptyHeader)
                ddl.Items.Add(new ListItem(headerText, ""));

            string layCode = string.Empty;
            int iBmLen = 0;
            string sNodeMc = string.Empty;

            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        layCode = iReader["LAYCODE"].ToString();

                        iBmLen = layCode.Length / iCodeLen;                        
                        sNodeMc = string.Empty;
                        for (int j = 0; j < iBmLen - 1; j++)
                        {
                            sNodeMc += "\u3000";
                        }
                        li = new ListItem(sNodeMc + iReader["NAME"].ToString(), iReader["ID"].ToString());
                        ddl.Items.Add(li);
                        
                    }
                }
            }
            catch (ArithmeticException ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "005", //数学运行 异常
                    paramInfo = "参数:【" + iCodeLen.ToString() + "】"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
                        
            sbCmdText = null;
        }



        /// <summary>
        /// 绑定通用listbox
        /// </summary>
        /// <param name="lstBox">listbox 控件</param>
        /// <param name="lstData">要绑定的数据集合</param>
        /// <param name="isSetSelValue">是否有默认选中项</param>
        /// <param name="selValue">默认选中值</param>
        public static void BindListBox(ref ListBox lstBox, List<MsKeyValue> lstData, bool isSetSelValue, string selValue)
        {
            lstBox.Items.Clear();
            if (null == lstData || lstData.Count == 0) return;

            foreach (MsKeyValue eKeyVal in lstData)
            {
                lstBox.Items.Add(new ListItem { Text = eKeyVal.val, Value = eKeyVal.key });
            }

            if (isSetSelValue)
            {
                MsKeyValue selItem = new MsKeyValue { val = string.Empty, key = selValue };
                KeyValComparer comparer = new KeyValComparer();
                bool bExist = lstData.Contains(selItem, comparer);
                if (bExist) {  //如果绑定的集合中包含选择项则设置该项为选中状态
                    lstBox.SelectedValue = selValue;
                }
                comparer = null;
                selItem = null;
            }
            
        }

        /// <summary>
        /// 绑定通用radiobuttonlist
        /// </summary>
        /// <param name="lstRadio">radiobuttonlist 控件</param>
        /// <param name="lstData">要绑定的数据集合</param>
        /// <param name="isSetSelValue">是否有默认选中项</param>
        /// <param name="selValue">默认选中值</param>
        public static void BindRadioList(ref RadioButtonList lstRadio, List<MsKeyValue> lstData, bool isSetSelValue, string selValue)
        {
            lstRadio.Items.Clear();
            if (null == lstData || lstData.Count == 0) return;

            foreach (MsKeyValue eKeyVal in lstData)
            {
                lstRadio.Items.Add(new ListItem { Text = eKeyVal.val, Value = eKeyVal.key });
            }

            if (isSetSelValue) {
                MsKeyValue selItem = new MsKeyValue { val = string.Empty, key = selValue };
                KeyValComparer comparer = new KeyValComparer();
                bool bExist = lstData.Contains(selItem, comparer);
                if (bExist) {  //如果绑定的集合中包含选择项则设置该项为选中状态
                    lstRadio.SelectedValue = selValue;
                }

                comparer = null;
                selItem = null;
            }

        }
        #endregion

    }
}
